package com.idealighter.game.games.foursshop.manager;

import com.alibaba.fastjson.TypeReference;

import com.google.inject.Inject;

import com.idealighter.game.core.common.Game;
import com.idealighter.game.games.foursshop.struct.FoursShopTable;
import com.idealighter.game.prizepool.manager.RoomPrizePoolMgrScript;
import com.idealighter.game.prizepool.struct.control.FoursShopControl;
import com.idealighter.game.prizepool.struct.room.ControlStrategy;
import com.idealighter.game.prizepool.struct.room.RoomPrizePool;
import com.idealighter.utils.code.RandCodeUtil;

/**
 * 4s店控制.
 */

public class FourShopControlScript {

  @Inject
  private RoomPrizePoolMgrScript roomPrizePoolMgr;
  @Inject
  private FoursShopMgr foursShopMgr;

  private static final TypeReference<FoursShopControl> FOUR_SHOP_CONTROL_TYPE_REFERENCE =
      new TypeReference<FoursShopControl>() {};

  /**
   * 控制开奖.
   *
   * @param table .
   */
  public int controlReward(FoursShopTable table) {
    int result = 0;
    boolean win = false;
    RoomPrizePool defaultRoomPrizePool =
        roomPrizePoolMgr.defaultRoomPrizePool(Game.FOURS_SHOP, table.room.getId());
    if (defaultRoomPrizePool != null) {
      ControlStrategy strategy = defaultRoomPrizePool.abledControlStrategy();
      if (strategy != null) {
        FoursShopControl foursShopControl = strategy.control(FOUR_SHOP_CONTROL_TYPE_REFERENCE);
        if (foursShopControl != null) {
          win = RandCodeUtil.random(
              foursShopControl.getLoseRatio() + foursShopControl.getWinRatio()) >= foursShopControl
                  .getLoseRatio();
        } else {
          result = 3;
        }
      } else {
        result = 3;
      }
    } else {
      result = 3;
    }
    if (result != 3) {
      result = win ? 0 : 1;
    }
    return result;
  }

  /**
   * 结算房间奖池.
   *
   * @param table .
   */
  public void balanceControl(FoursShopTable table) {
    long gold = foursShopMgr.convertGold(table.room.getId().intValue(), table.earn);
    RoomPrizePool seatRoomPrizePool =
        roomPrizePoolMgr.defaultRoomPrizePool(Game.FOURS_SHOP, table.room.getId());
    if (seatRoomPrizePool != null) {
      long totalGold = foursShopMgr.convertGold(table.room.getId().intValue(), gold);
      long prize = seatRoomPrizePool.getPrize().get();
      prize += totalGold;
      seatRoomPrizePool.getPrize().getAndSet(prize);
    }
  }
}

